/**
 * 事件总线
 * EventBus
 */
export class EventEmitter {
  constructor() {
    this.eventQueue = {};
  }

  // 监听
  on(names, callback, handle = null, once = false) {
    if (!Array.isArray(names)) {
      names = [names];
    }
    // names.split(/\s+/).map(name => {
    names.forEach((name) => {
      if (!this.eventQueue[name]) {
        this.eventQueue[name] = [];
      }
      this.eventQueue[name].push({ callback, handle, once });
    });
  }

  // 触发
  emit(name, ...args) {
    this.eventQueue[name] = (this.eventQueue[name] || []).filter(({ callback, handle, once }) => {
      // 触发事件
      try {
        (handle ? callback.bind(handle) : callback)(...args);
      } catch (e) {
        console.warn(e);
      }
      return !once;
    });
  }

  // 移除
  remove(name, callback = false, handle = null) {
    if (!this.eventQueue[name]) return;
    // 清除所有事件
    if (arguments.length === 1) this.eventQueue[name] = [];
    // 过滤掉需要删除的事件
    this.eventQueue[name] = (this.eventQueue[name] || []).filter(({ callback: cb, handle: hd }) => {
      const isTargetFunc = cb === callback;
      const isTargetHandler = handle === hd;
      if (handle) {
        return !(isTargetFunc && isTargetHandler);
      } else if (callback) {
        return !isTargetFunc;
      } else {
        return false;
      }
    });
  }
}
